import logging
import inspect
import sys

import os
import azure.functions as func
import json

logger = logging.getLogger(__name__)

CURRENTDIR = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
PARENTDIR = os.path.dirname(CURRENTDIR)
sys.path.insert(0, CURRENTDIR)
sys.path.insert(0, PARENTDIR)


from web.webapi.progressiveapi import CookieGen as progCG
from web.webapi.webapi import CookieGen as webCG


class AkamaiException(BaseException):
    pass


class SignatureException(AkamaiException):
    pass


def str2bool(v):
    return v.lower() in ("yes", "true", "t", "1")


def main(req: func.HttpRequest) -> func.HttpResponse:
    try:
        body = req.get_json()
        logger.debug(json.dumps(body))
        version = body.get("version")
        if isinstance(version, float):
            version = str(version)
        if "sequence" in body.keys():
            seq = body.get("sequence")
            if isinstance(seq, bool):
                sequenceapi = seq
            else:
                sequenceapi = str2bool(seq)
        else:
            sequenceapi = False

        cookie = body.get("cookie")
        url = body.get("url")
        if "useragent" in body.keys():
            useragent = body.get("useragent")
        else:
            useragent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/605.1.15 (KHTML, like Gecko) Safari/605.1.15"
        if version == "1.43":
            if sequenceapi:
                outlist = []
                t = progCG(cookie=cookie, url=url, useragent=useragent)
                for _ in range(5):
                    outlist.append(t.iterate())
                return func.HttpResponse(
                    body=json.dumps({"sensordata": outlist, "version": "1.43"}),
                    headers={"Content-Type": "application/json"}, status_code=200
                )
            else:
                t = webCG()
                return func.HttpResponse(
                    body=json.dumps(
                        {
                            "sensordata": t.get_sensor_data(
                                url=url, cookie=cookie, useragent=useragent
                            ),
                            "version": "1.43",
                        }
                    ),
                    headers={"Content-Type": "application/json"}, status_code=200
                )
        else:
            return func.HttpResponse(
                body=json.dumps({"error": "version unavailable"}),
                status_code=400,
                headers={"Content-Type": "application/json"},
            )
    except (KeyError, ValueError):
        logger.error(json.dumps(req.get_json()), exc_info=True)
        return func.HttpResponse(
            body=json.dumps({"error": "request error - missing fields"}),
            status_code=400,
            headers={"Content-Type": "application/json"},
        )
    except Exception as e:
        # return func.HttpResponse(body=json.dumps({"error":e.message}, status_code=400, headers={"Content-Type": "application/json"}))
        logger.error("error: {}".format(str(e.__str__).split(" ")[3]), exc_info=True)
        return func.HttpResponse(
            body=json.dumps({"error": "request error {}".format(str(e.args))}),
            status_code=400,
            headers={"Content-Type": "application/json"},
        )
